package vkmc;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import run.Main;
import run.std;
import vkmc.Crawler.Found;
import vkmc.Crawler.Search;
import vkmc.Crawler.Song;

public class Actions
{
	private Crawler crlw;
	private String[][] songs;
	private boolean done;
	private String searchKey;
	private List<AsyncDownloader> dls = new ArrayList<AsyncDownloader>();
	
	public static final int NAME_INDEX = 0;
	public static final int LENGTH_INDEX = 1;
	public static final int BITRATE_INDEX = 2;
	public static final int URL_INDEX = 3;
	
	private static final char[] ILLEGAL_CHARACTERS = { '/', '\n', '\r', '\t', '\0', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':' };
	
	public Actions()
	{
		done = false;
		try
		{
			crlw = new Crawler(Settings.getUsername(), Settings.getPassword());
		}
		catch (Exception ex){}
	}
	
	public boolean loggedIn()
	{
		return crlw.IsLoggedIn();
	}
	
	public void login()
	{
		new Thread(new Runnable()
		{
			public void run()
			{
				Main.gui.startBusyAnimation();
				if (!crlw.IsLoggedIn()){
                    Main.gui.toggleSearchBtn(false);
                    crlw.Login();
                }
				while (!crlw.IsLoggedIn())
				{
					try
					{
						Thread.sleep(1);
					}
					catch (InterruptedException e){}
				}
                Main.gui.toggleSearchBtn(true);
				Main.gui.stopBusyAnimation();
				Main.gui.startSearch();
			}
		}, "LoginThread").start();
	}
	
	public void setSearchKey(String s)
	{
		searchKey = s;
	}
	
	public void download(String url, String fname, final int row)
	{
		Settings.createDonwloadsDir();
		
		String filename = fname	+ ".mp3";
		for (int i = 0; i < ILLEGAL_CHARACTERS.length; i++)
		{
			filename = filename.replace(ILLEGAL_CHARACTERS[i], ' ');
		}

		String path = Settings.getDownloadDirectory() + "/" + filename;
		File dlf = new File(path);
		if (dlf.exists())
		{
			dlf.delete();
		}

		final AsyncDownloader dl = new AsyncDownloader(url, path);
		dls.add(dl);

		dl.addProgressChangedListener(new ProgressChangedListener()
		{
			public void ProgressChanged(ProgressChanged evt)
			{
				int progress = dl.getProgress();
				if (progress == -2)
				{
					Main.gui.setProgress(-1, row);
					return;
				}
				Main.gui.setProgress(progress, row);
			}
		});
	}
	
	public void cancelDownload(int row)
	{
		dls.get(row).cancelDownload();
	}
	
	public void Search()
	{
		new Thread(new Runnable()
		{
			public void run()
			{
				try
				{
					final Search srch = crlw.Search(searchKey, 0);
					srch.addFoundListener(new Crawler.FoundListener()
					{
						public void Found(Found evt)
						{
							List<Song> result = srch.getResult();
							ArrayList<String[]> arr = new ArrayList<String[]>();
							if (result != null)
							{
								for (Song song : result)
								{
									if (std.isNumeric(song.BitRate))
									{
										int sb = std.toint(song.BitRate);
										int mb = std.toint(Settings.getMinBitrate());
										if (sb < mb)
											continue;
									}
									float s = 0;
									int i = 0;
									final String[] units = {"B", "KB", "MB", "GB"};
									if (std.isNumeric(song.Length))
									{
										s = std.toint(song.Length);
										while (s >= 1024 && i < 4)
										{
											s *=  0.0009765625;
											i++;
										}
									}
									String size = String.format("%.2f   %s", s, units[i]);
									arr.add(new String[]{ song.Name, song.Duration, song.BitRate, size, song.Url});
								}
								done = true;
								songs = new String[arr.size()][5];
								int i = 0;
								for (String[] s : arr)
								{
									songs[i] = s;
									i++;
								}
							}
						}
					});
				}
				catch (Exception ex){ex.printStackTrace();}
				try
				{
					while (!done){Thread.sleep(1);}
				}
				catch (Exception ex){}
				Main.gui.setData(songs);
				done = false;
			}
		}, "SearchThread").start();
	}
}
